package com.leather.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leather.admin.entity.Permission;
import com.leather.admin.entity.Role;
import com.leather.admin.entity.RolePermission;
import com.leather.admin.mapper.PermissionMapper;
import com.leather.admin.mapper.RoleMapper;
import com.leather.admin.mapper.RolePermissionMapper;
import com.leather.admin.service.RoleService;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public Result addRole(Role role) {
        if (StringUtils.isBlank(role.getRoleName())) {
            return Result.error(CodeMsg.EMPTY_ROLENAME);
        }
        if (null != getRole(role.getRoleName())) {
            return Result.error(CodeMsg.DUPPY_ROLENAME);
        }
        role.setCreateTime(new Date());
        role.setId(0);
        if (save(role)) {
            return Result.success(role);
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

    @Override
    public Role getRole(String roleName) {
        if (StringUtils.isBlank(roleName)) {
            return null;
        }
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", roleName);
        return getOne(queryWrapper);
    }

    @Override
    public Role getRoleById(int roleId) {
        if (roleId <= 0) {
            return null;
        }
        return getById(roleId);
    }

    @Override
    public JSONArray getTreeByRoleId(Integer roleId) {

        JSONArray systems = new JSONArray();


        //获取角色已经有的权限
        List<Permission> rolePermissions = roleMapper.getRolePermissions(roleId);
        //获取所有权限
        List<Permission> permissions = permissionMapper.selectList(null);
        //添加所有的目录
        for (Permission permission : permissions) {
            if (permission.getIsParent() == 0) {
                JSONObject node = new JSONObject();
                node.put("id", permission.getId());
                node.put("name", permission.getPermissionName());
                node.put("nocheck", false);
                node.put("open", true);
                for (Permission rolePermission : rolePermissions) {
                    if (rolePermission.getId().intValue() == permission.getId().intValue()) {
                        node.put("checked", true);
                    }
                }
                systems.add(node);
            }
        }
        //添加目录下的菜单
        //遍历菜单
        if (systems.size() > 0) {
            for (Object object : systems) {
                List<Permission> subPermisson = new ArrayList<>();
                int id = ((JSONObject) object).getIntValue("id");
                permissions.forEach((item) -> {
                    if (item.getParentId() == id) {
                        subPermisson.add(item);
                    }
                });
                if (subPermisson.size() == 0) {
                    continue;
                }
                JSONArray menu = new JSONArray();
                for (Permission pr : subPermisson) {
                    JSONObject node2 = new JSONObject();
                    node2.put("id", pr.getId());
                    node2.put("name", pr.getPermissionName());
                    for (Permission rolePermission : rolePermissions) {
                        if (rolePermission.getId().intValue() == pr.getId().intValue()) {
                            node2.put("checked", true);
                        }
                    }
                    menu.add(node2);
                }
                ((JSONObject) object).put("children", menu);
            }
        }
        return systems;
    }

    @Transactional
    @Override
    public Result setRolePermission(int roleId, JSONArray permissions) {
        if (roleId <= 0) {
            return Result.error(CodeMsg.ROLE_NOT_EXIST);
        }
        int result;
        for (Object object : permissions) {
            int pid = ((JSONObject) object).getIntValue("id");
            boolean check = ((JSONObject) object).getBoolean("checked");
            if (check) {
                try {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setId(0);
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(pid);
                    result = rolePermissionMapper.insert(rolePermission);
                    if (result <= 0) {
                        throw new RuntimeException("内部错误!");
                    }
                } catch (Exception e) {
                    return Result.error(CodeMsg.DUPPY_PERMISION);
                }
            } else {
                QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("role_id", roleId).eq("permission_id", pid);
                result = rolePermissionMapper.delete(queryWrapper);
                if (result <= 0) {
                    throw new RuntimeException("内部错误!");
                }
            }
        }
        return Result.success("设置成功!");
    }

}
